import Vue from 'vue';
import VueRouter from 'vue-router';
import store from './vuex/store'

Vue.use(VueRouter);

var router;
export default function() {
  //未实例化过，实例化一个单例
  if(!router){
    router=new VueRouter({});
    router.beforeEach((transition) => {
      //如果要跳转的页面已打开，则切换到该页面对应的标签页。
      var toTabLink=decodeURI(transition.to.path);
      if(toTabLink!=store.state.tab.link){
        for(let i=0,l=store.state.tabs.length;i<l;i++){
          if(toTabLink==store.state.tabs[i].link){
            store.state.tab=store.state.tabs[i];
            sessionStorage.setItem('tab',JSON.stringify(store.state.tab));
          }
        }
      }

      if(transition.to.oauth) { // 需要登入信息的页面
        // 判断是否已经的登入过
        if(!store.state.token) {
          // 没有登入信息, 跳转到登入页面
          transition.redirect('/login');
          return;
        }

        // 已经有登入信息
        transition.next();
      } else {// 不需要登入信息的页面
        transition.next();
      }

    });
  }
  // 测试路由
  // router.map({
  //   '/test': {
  //     frame: false,
  //     component: function(resolve) {
  //       require(['./views/test.vue'], resolve);
  //     }
  //   }
  // });

  // 基础路由
  router.map({
    '*': {
      frame: false,
      component: function(resolve) {
        require(['./views/404.vue'], resolve);
      }
    },
    '/login': {
      frame: false,
      component: function(resolve) {
        require(['./views/login.vue'], resolve);
      }
    },
    '/': {
      frame: false,
      oauth: true,
      component: function(resolve) {
        require(['./views/login.vue'], resolve);
      }
    },
    '/index': {
      oauth: true,
      frame: true,
      component: function(resolve) {
        require(['./views/index.vue'], resolve);
      }
    }
  });
  
  router.map({
    '/add': {
      frame: true,
      oauth: true,
      component: function(resolve) {
        require(['./views/add/publish.vue'], resolve);
      }
    },
    'add/publish': {
      frame: true,
      oauth: true,
      component: function(resolve) {
        require(['./views/add/publish.vue'], resolve);
      }
    },
    'add/detail': {
      frame: true,
      oauth: true,
      component: function(resolve) {
        require(['./views/add/detail.vue'], resolve);
      }
    }
  });

  return router;
}
